package se.thoka.twt.client.form;

import se.thoka.twt.client.utils.DOMUtil;
import se.thoka.twt.client.widgets.TWTPanel;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class TWTFormRenderer {
	
	private static TWTFormRenderer instance;
	
	private TWTFormFieldRenderer defaultRenderer;
	
	public TWTFormRenderer() {}
	
	public static TWTFormRenderer getInstance() {
		if (instance == null) {
			instance = GWT.create(TWTFormRenderer.class);
		}
		
		return instance;
	}
	
	public TWTFormFieldRenderer getRenderer(TWTFormField<?> formField) {
		if (defaultRenderer == null) {
			defaultRenderer = new DefaultTWTFormFieldRenderer();
		}
		
		return defaultRenderer;
	}
	
	public Widget renderForm(TWTForm form) {
		VerticalPanel result = new VerticalPanel();
		for (TWTFormField<?> field : form.getFields()) {
			result.add(getRenderer(field).render(field, true));
		}
		
		return result;
	}
	
	public void renderFormById(TWTPanel formPanel, TWTForm form) {
		for (TWTFormField<?> field : form.getFields()) {
			String id = field.getId();
			Element fieldElem = DOMUtil.getChildById(formPanel, id);
			
			if (fieldElem != null) {
				Element labelElem = DOMUtil.getChildById(formPanel, id + "-LABEL");
				boolean labelElemFound = labelElem != null;
				TWTFormFieldRenderer renderer = getRenderer(field);
				Widget fieldWidget = renderer != null ? renderer.render(field, !labelElemFound) : field;
				formPanel.add(fieldWidget, fieldElem);

				if (labelElemFound) {
					Label label = new Label(field.getLabel(), false);
					label.addStyleName(TWTFormField.FORM_FIELD_LABEL_STYLE);
					formPanel.add(label, labelElem);
				}
			}
		}
	}
	
	private static class DefaultTWTFormFieldRenderer implements TWTFormFieldRenderer {
		@Override
		public Widget render(TWTFormField<?> formField, boolean includeLabel) {
			Widget result;
			
			if (includeLabel) {
				VerticalPanel panel = new VerticalPanel();
				Label label = new Label(formField.getLabel(), false);
				label.addStyleName(TWTFormField.FORM_FIELD_LABEL_STYLE);
				panel.add(label);
				panel.add(formField);
				result = panel;
			} else {
				result = formField;
			}
			
			return result;
		}
	}
}
